package com.revelvy.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    // 关联配置文件
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    // 后台监控
    //      SpringBoot内置servlet容器 无web.xml
    //      故用ServletRegistrationBean替换web.xml的DispatcherServlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // 初始化参数
        HashMap<String, String> initParameters = new HashMap<>();
        initParameters.put("loginUsername", "revelvy");
        initParameters.put("loginPassword", "2228342677");
        initParameters.put("allow", "");
        // 禁止xxx访问
//        initParameters.put("a","192.168.0.1");
        bean.setInitParameters(initParameters);
        return bean;
    }

    // 过滤器
    //      替换web.xml的filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        // 初始化参数
        Map<String, String> initParameters = new HashMap<>();
        // 过滤 排除 不统计这些东西
        initParameters.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }
}
